﻿using BLL;
using HighThroughput.Common;
using HighThroughput.ShareData;
using Models;
using Ozone.BLL;
using Ozone.Help;
using Ozone.Models;
using Ozone.Views.Widget;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using static HighThroughput.ShareData.ReadData;


namespace Ozone.Views.MethodCenter
{
    /// <summary>
    /// UCMethodCenterMain.xaml 的交互逻辑
    /// </summary>
    public partial class UCMethodCenterMain : UserControl
    {
        private static CancellationTokenSource _cts;

        //使用异步协作式取消  
        //使用场景 适用于开始停止 这种场景  不使用于开始 暂停 继续 停止的场景
        // 1：‌非强制中断‌线程
        //调用方无法直接终止任务，只能通过发送取消请求（调用 Cancel()）‌
        //2：‌任务主动响应‌
        //任务需周期性检查取消令牌（如 token.IsCancellationRequested 或 ThrowIfCancellationRequested()），并自主决定何时终止‌
        //3:/‌安全退出机制‌
        //抛出 OperationCanceledException 通知调用方任务已被取消，同时允许任务清理资源后再退出‌
        // 检查取消请求  
        //token.ThrowIfCancellationRequested();
        //抛出 OperationCanceledException 通知调用方任务已被取消
        //运行方法
        List<Method> MethodList = null;

        Method RunMethod = null;

        //开始运行时间
        DateTime dtStartRun;

        public UCMethodCenterMain()
        {
            InitializeComponent();
            //默认加载第一条方法
            MethodList = MethodBLL.GetALLMethodList();
            //刷新列表
            refreshMethodMain();
            //默认选择第一行
            if (dgMethodList.Items.Count > 0)
            {
                dgMethodList.SelectedIndex = 0;
            }
        }



        #region 方法序列操作

        /// <summary>
        /// 执行方法操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonMethodMain_click(object sender, System.Windows.RoutedEventArgs e)
        {
            string tag = ((Button)sender).Tag.ToString();

            if (tag == "ADD")
            {
                WindowMethod form = new WindowMethod("新建方法", "");
                form.ShowDialog();
                if (form.isOK)
                {
                    string methodName = form.m_strName;
                    string Message = string.Empty;
                    bool IsSuccess = MethodBLL.AddMethod(methodName, out Message);
                    if (!IsSuccess)
                    {
                        if (MessageBox.Show(Message, "提示",
                          MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes)
                        {
                            return;
                        }
                    }
                }
            }

            if (tag == "UPDATE")
            {
                if (dgMethodList.SelectedItems != null)
                {
                    Method method = (Method)dgMethodList.SelectedItem;
                    if (method != null)
                    {
                        WindowMethod form = new WindowMethod("修改方法", method.MethodName);
                        form.ShowDialog();
                        if (form.isOK)
                        {
                            method.MethodName = form.m_strName;
                            string Message = string.Empty;
                            bool IsSuccess = MethodBLL.UpdateMethod(method, out Message);
                            if (!IsSuccess)
                            {
                                if (MessageBox.Show(Message, "提示",
                                  MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes)
                                {
                                    return;
                                }
                            }
                        }
                    }

                }
            }

            if (tag == "DEL")
            {
                if (dgMethodList.SelectedItems != null)
                {
                    Method method = (Method)dgMethodList.SelectedItem;
                    if (method != null)
                    {
                        if (MessageBox.Show("确认要删除方法吗", "提示",
        MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes)
                        {
                            return;
                        }
                        MethodBLL.DeleteMethod(method.FID);
                    }
                }
                if (dgMethodList.SelectedItems.Count == 0)
                {
                    return;
                }
            }
            MethodList = MethodBLL.GetALLMethodList();
            refreshMethodMain();
        }


        /// <summary>
        /// 执行方法序列操作 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonMethodItem_click(object sender, RoutedEventArgs e)
        {
            string tag = ((Button)sender).Tag.ToString();
            if (dgMethodList.SelectedItems != null)
            {
                Method method = (Method)dgMethodList.SelectedItem;
                //添加
                if (tag == "ADD")
                {
                    MethodItem methodItem = new MethodItem();
                    WindowMethodItem from = new WindowMethodItem(methodItem);
                    if (!from.ShowModal())
                    {
                        return;
                    }
                    methodItem = from.MethodItemModelConfig;
                    method.methodItem.Add(methodItem);
                    MethodBLL.UpdateMethodExecSerial(method.FID, method.methodItem);


                }
                //修改
                if (tag == "UPDATE")
                {
                    if (dgMethodItem.SelectedItem != null)
                    {
                        MethodItem methodItem = (MethodItem)dgMethodItem.SelectedItem;
                        WindowMethodItem from = new WindowMethodItem(methodItem);
                        if (!from.ShowModal())
                        {
                            return;
                        }
                        int nIndexItem = dgMethodItem.Items.IndexOf(dgMethodItem.SelectedItem);
                        method.methodItem[nIndexItem] = from.MethodItemModelConfig;
                        MethodBLL.UpdateMethodExecSerial(method.FID, method.methodItem);
                    }
                }


                if (tag == "DEL")
                {
                    if (dgMethodItem.SelectedItem != null)
                    {
                        MethodItem methodItem = (MethodItem)dgMethodItem.SelectedItem;
                        if (MessageBox.Show("确认要删除方法中的序列吗?", "提示",
                          MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes)
                        {
                            return;
                        }
                        method.methodItem.Remove(methodItem);
                        MethodBLL.UpdateMethodExecSerial(method.FID, method.methodItem);
                    }

                }
                //刷新页面
                refreshMethodItem(method);
            }
        }





        /// <summary>
        /// 选择方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgMethodMain_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
        {
            if (dgMethodList.SelectedItems.Count == 0)
            {
                return;
            }
            int nIndex = dgMethodList.Items.IndexOf(dgMethodList.SelectedItem);
            Method method = MethodList[nIndex];
            refreshMethodItem(method);
        }

        #endregion



        #region  页面刷新


        /// <summary>
        /// 刷新UI页面
        /// </summary>
        private void RefreshUIThread()
        {
            bool bGo = true;
            Task.Run(() =>
            {
                while (bGo)
                {

                    DateTime timeB = DateTime.Now;  //获取当前时间
                    TimeSpan ts = DateTime.Now - dtStartRun;    //计算时间差
                    try
                    {
                        this.Dispatcher.Invoke(new Action(
                            delegate
                            {
                                try
                                {
                                    if (!(ReadData.Entity.methodItemRunState == MethodItemRunState.Runing))
                                    {
                                        setRunStatusView(false);
                                        dgMethodItem.Items.Refresh();
                                        bGo = false;
                                    }
                                    else
                                    {
                                        lblRunTime.Content = "运行：" + Tools.sec_to_hms((long)ts.TotalSeconds);
                                        dgMethodItem.Items.Refresh();
                                    }
                                }
                                catch (Exception ex)
                                {
                                    LogHelper.Error("刷新页面异常", ex);
                                }
                            }
                            )
                        );
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Error("刷新方法运行页面异常", ex);
                    }
                    Thread.Sleep(1000);
                }
            });
        }
        /// <summary>
        /// 刷新方法列表
        /// </summary>
        public void refreshMethodMain()
        {
            dgMethodList.ItemsSource = null;
            dgMethodList.ItemsSource = MethodList;
        }
        /// <summary>
        /// 刷新方法序列列表
        /// </summary>
        /// <param name="method"></param>
        public void refreshMethodItem(Method method)
        {
            dgMethodItem.ItemsSource = null;
            dgMethodItem.ItemsSource = method.methodItem;
        }

        #endregion




        #region  页面按钮状态
        //设置运行状态界面控制 False:停止 True：运行中
        private void setRunStatusView(bool RunState)
        {
            bool bRunFlag = RunState;
            //运行按钮
            btnRun.IsEnabled = !bRunFlag;
            //停止按钮
            btnStop.IsEnabled = bRunFlag;
            //方法列表
            gridSelectMethod.IsEnabled = !bRunFlag;

            spEdit.IsEnabled = !bRunFlag;

            if (bRunFlag)
            {
                lblRunTime.Visibility = Visibility.Visible;
                btnRunFlag.Visibility = Visibility.Visible;
            }
            else
            {
                lblRunTime.Visibility = Visibility.Hidden;
                btnRunFlag.Visibility = Visibility.Hidden;
            }
        }

        #endregion






        private async void buttonRun_click(object sender, RoutedEventArgs e)
        {
            string tag = ((Button)sender).Tag.ToString();
            if (dgMethodList.SelectedItem == null)
            {
                MessageBox.Show("请选择要执行方法", "提示",
                       MessageBoxButton.OK, MessageBoxImage.Warning);
                {
                    return;
                }
            }
            RunMethod = (Method)dgMethodList.SelectedItem;
            //运行方法
            if (tag == "run")
            {
                //先设置界面按钮状态
                setRunStatusView(true);
                await Task.Run(() =>
                {
                    RunMethodThread();
                });
            }
            //停止
            if (tag == "stop")
            {
                setRunStatusView(false);
                StopMethod();
            }
            //设备初始化
            if (tag == "InitDevice")
            {
                bool isSuccess = await DeviceInit();
                // 根据结果更新UI
                if (isSuccess)
                {
                    btnRun.IsEnabled = true;
                }
                else
                {
                    MessageBox.Show("设备初始化失败");
                }
            }
        }

        /// <summary>
        /// 全流程执行方法
        /// </summary>
        private async void RunMethodThread()
        {
            try
            {
                ReadData.Entity.methodItemRunState = MethodItemRunState.Runing;
                dtStartRun = DateTime.Now;

                RefreshUIThread();
                _cts = new CancellationTokenSource();
                var token = _cts.Token;
                MethodCenterBLL methodCenterBLL = new MethodCenterBLL();
                await methodCenterBLL.RunMethodThreadAsync(token, RunMethod);
            }
            catch (Exception ex)
            {
                LogHelper.Error("执行全流程发送异常", ex);
            }
        }

        /// <summary>
        /// 停止
        /// </summary>
        /// <returns></returns>
        private bool StopMethod()
        {
            try
            {
                _cts.Cancel();
                ReadData.Entity.methodItemRunState = MethodItemRunState.Stop;
                this.Dispatcher.Invoke(new Action(
                      delegate
                      {
                      }
                      )
                    );
            }
            catch (Exception ex)
            {
                LogHelper.Error("停止全流程异常", ex);
            }
            LogHelper.Debug("全流程手动停止");
            return true;
        }



        /// <summary>
        /// 设备初始化
        /// </summary>
        /// <returns></returns>
        private async Task<bool> DeviceInit()
        {
            bool IsInitSuccess = false;
            try
            {

                IsInitSuccess = await DeviceInitBLL.InitDeviceAsync();
                if (IsInitSuccess)
                {
                    LogHelper.Debug("设备全部初始化成功！");
                }
                else
                {
                    LogHelper.Debug("设备全部初始化失败！");
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error("设备初始化异常", ex);
            }
            return IsInitSuccess;
        }



















































    }
}

